<!-- 发表话题页 -->
<template>
    <!-- 页头 :sticky="false"关闭浮动置顶功能 -->
    <Header :sticky="false"/>

    <div class="main">
        <div class="main-container wrap backgroundModule main-fullScreen">
            <div class="addTopicModule" >
                <el-form label-position="right" :rules="rules" ref="formMobileRef" :model="form" class="iconForm-container" size="large" v-if="form.allowTopic">
                    
                    <el-row>
                        <el-col :span="5" >
                            <el-form-item :error="error.tagId" >
                                <!--no-match-text="还没有标签" placeholder="选择标签"-->
                                <el-select v-model="form.tagIdGroup" @focus="queryTagList" @change="selectedTag" :no-match-text="t('addTopic.10')" :placeholder="t('addTopic.20')">
                                    <template v-for="tag in form.tagList">
                                        <el-option-group :key="'group-'+tag.id" :label="tag.name" v-if="tag.childNodeNumber >0">
                                            <el-option v-for="childTag in tag.childTag" :key="childTag.id" :label="childTag.name" :value="childTag.id" :disabled="!isAllowTag(childTag.id)"><div class="option-group">{{ childTag.name }}</div></el-option>
                                        </el-option-group>
                                        <el-option v-else :key="tag.id" :label="tag.name" :value="tag.id" :disabled="!isAllowTag(tag.id)"></el-option>
                            
                                    </template>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="17" style="margin-left: 8px;">
                            <el-form-item :error="error.title" >
                                 <!--placeholder="标题"-->
                                <el-input v-model.trim="form.title" :placeholder="t('addTopic.30')" maxlength="90" clearable></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <!--红包-->
                    <el-form-item :label="t('addTopic.40')" v-if="form.showRedEnvelopeText" >
                        <el-switch v-model="form.showRedEnvelopeForm" @click="selectRedEnvelopeType"></el-switch>
                    </el-form-item>
                    <div v-if="form.showRedEnvelopeForm">
                        <el-form-item>
                            <el-radio-group v-model="form.giveRedEnvelope_type" @change="selectRedEnvelopeType()">
                                <el-radio :label="20">{{t('addTopic.50')}}</el-radio><!--随机金额红包-->
                                <el-radio :label="30">{{t('addTopic.60')}}</el-radio><!--固定金额红包-->
                            </el-radio-group>
                        </el-form-item>
                        <!--红包总金额 placeholder="输入金额" -->
                        <el-form-item :error="error.totalAmount" v-if="form.giveRedEnvelope_type == 20">
                            <!-- 红包总金额 <el-input v-model.trim="form.giveRedEnvelope_totalAmount" :placeholder="i18n.t('addTopic.80')" maxlength="12" @input="totalAmountCalculate()" clearable style="width: 150px;margin-left:10px;margin-right:10px;"></el-input>元 -->
                            <span class="form-text">
                                <i18n-t keypath="addTopic.70" scope="global">
                                    <template #p1>
                                        <el-input v-model.trim="form.giveRedEnvelope_totalAmount" :placeholder="t('addTopic.80')" maxlength="12" @input="totalAmountCalculate()" clearable style="width: 150px;margin-left:10px;margin-right:10px;"></el-input>
                                    </template>
                                </i18n-t>
                            </span>
                            <span class="help-text">
                                <!--合计总金额不能少于 {p1} 元； -->
                                <span v-if="parseFloat(form.giveRedEnvelopeAmountMin) >0">{{t('addTopic.90',{'p1': form.giveRedEnvelopeAmountMin})}}</span>	
								<!--合计总金额不能超过 {p1} 元； -->
                                <span v-if="form.giveRedEnvelopeAmountMax != null && parseFloat(form.giveRedEnvelopeAmountMax) >0">{{t('addTopic.100',{'p1': form.giveRedEnvelopeAmountMax})}}</span>	
								<!--用户共有金额 {p1} 元-->
                                <span>{{t('addTopic.110',{'p1': form.deposit})}}</span>
                            </span>
                        </el-form-item>
                        <el-form-item :error="error.singleAmount" v-if="form.giveRedEnvelope_type == 30">
                            <!--单个红包金额 <el-input v-model.trim="form.giveRedEnvelope_singleAmount" placeholder="输入金额" maxlength="12" @input="singleAmountCalculate()" clearable style="width: 150px;margin-left:10px;margin-right:10px;"></el-input>元-->
                            <span class="form-text">
                                <i18n-t keypath="addTopic.120" scope="global">
                                    <template #p1>
                                        <el-input v-model.trim="form.giveRedEnvelope_singleAmount" :placeholder="t('addTopic.80')" maxlength="12" @input="singleAmountCalculate()" clearable style="width: 150px;margin-left:10px;margin-right:10px;"></el-input>
                                    </template>
                                </i18n-t>
                            </span>
                            <span class="help-text">
                                <!--合计总金额不能少于 {p1} 元；-->
                                <span v-if="parseFloat(form.giveRedEnvelopeAmountMin) >0">{{t('addTopic.90',{'p1': form.giveRedEnvelopeAmountMin})}}</span>	
								<!--合计总金额不能超过 {p1} 元；-->
                                <span v-if="form.giveRedEnvelopeAmountMax != null && parseFloat(form.giveRedEnvelopeAmountMax) >0">{{t('addTopic.100',{'p1': form.giveRedEnvelopeAmountMax})}}</span>	
								<!--用户共有金额 {p1} 元-->
                                <span>{{t('addTopic.110',{'p1': form.deposit})}}</span>
                            </span>
                        </el-form-item>
                        <el-form-item :error="error.giveQuantity">
                            <!--<el-input v-model.trim="form.giveRedEnvelope_giveQuantity" placeholder="输入数量" maxlength="8" @input="singleAmountCalculate()" clearable style="width: 100px;margin-right:10px;"></el-input>个红包-->
                            <i18n-t keypath="addTopic.180" scope="global">
                                <template #p1>
                                    <el-input v-model.trim="form.giveRedEnvelope_giveQuantity" :placeholder="t('addTopic.170')" maxlength="8" @input="singleAmountCalculate()" clearable style="width: 100px;margin-right:10px;"></el-input>
                                </template>
                            </i18n-t>
                        </el-form-item>
                        <el-form-item :error="error.redEnvelopeLimit">
                            <!--合计总金额-->
                            {{t('addTopic.190')}}<span class="totalAmountView">{{form.giveRedEnvelope_totalAmountView}}</span>
                        </el-form-item>
                    </div>

                    <!--发起投票-->
                    <el-form-item :label="t('addTopic.280')" v-if="form.isVoteView">
                        <el-switch v-model="form.isVote" ></el-switch>
                    </el-form-item>
                    <!--投票标题-->
                    <el-form-item :label="t('addTopic.300')" v-if="form.isVote" :required="true" :error="error.voteTitle" >
                        
                        <el-input v-model.trim="form.voteTitle" maxlength="150" :clearable="true" show-word-limit style="width: 850px;"></el-input>
                            
                    </el-form-item>
                    <!--投票类型-->
                    <el-form-item :label="t('addTopic.310')" v-if="form.isVote" :required="true">
                        <el-radio-group v-model="form.voteMaxChoice">
                            <el-radio :label="1">{{t('addTopic.320')}}</el-radio><!--单选-->
                            <el-radio :label="-1">{{t('addTopic.330')}}</el-radio><!--多选-->
                        </el-radio-group>
                    </el-form-item>
                    <!--投票截止时间-->
                    <el-form-item :label="t('addTopic.340')" v-if="form.isVote" :error="error.voteEndDate">
                         <span class="form-text">
                            <!--选择时间-->
                            <el-date-picker v-model="form.voteEndDate_format" type="datetime" format="YYYY-MM-DD HH:mm:ss" :placeholder="t('addTopic.350')"></el-date-picker>
                        </span>
                        <!--空值表示没有截止时间-->
                        <div class="help-text" >{{t('addTopic.360')}}</div>
                    </el-form-item>
                    <!--投票选项-->
                    <el-form-item v-for="(voteOption, index) in form.voteOptions" v-if="form.isVote"  :label="t('addTopic.370')" :required="true" >
                        
                        <el-col :span="16">
                            <el-input v-model="voteOption.text" maxlength="50" :clearable="true" show-word-limit></el-input>
                        </el-col>
                        <el-col :span="6" :offset="1">
                            <!--上移-->
                            <el-button size="large" :icon="Top" circle @click.prevent="moveUp(voteOption)" :title="t('addTopic.380')"></el-button>
                            <!--下移-->
                            <el-button size="large" :icon="Bottom" circle @click.prevent="moveDown(voteOption)" :title="t('addTopic.390')"></el-button>
                            <!--删除-->
                            <el-button size="large" :icon="Delete" circle @click.prevent="removeItem(voteOption)" :title="t('addTopic.400')"></el-button>
                        </el-col>
                    </el-form-item>
                    <el-form-item v-if="form.isVote" :error="error.voteOption">
                        <!--增加投票选项-->
                        <div class="item-button"><el-button size="large" :icon="Plus" @click="addItem">{{t('addTopic.410')}}</el-button></div>
                    </el-form-item>

                    <el-form-item :error="error.content" >
                        <div v-show="!form.isMarkdown" style="width: 100%;">
                            <textarea :editorId="'addTopic'" ref="contentRef" style="width:100%;height:400px;visibility:hidden;"></textarea>
                        </div>
                        <div v-if="form.isMarkdown" style="width: 100%;">
                            <!--placeholder="请输入内容..."-->
                            <Editor  :editorId="'addTopic'" :value="form.markdownContent" :plugins="form.addTopicEditorPlugin" :locale="setMarkdownLanguage()" :editorConfig="markdownEditorConfig" :sanitize="addTopicSanitize" :placeholder="t('addTopic.200')" @change="handleMarkdownChange"/>
                        </div>
                    </el-form-item>

                    <el-form-item :error="error.captchaValue" prop="captchaValue" v-if="form.showCaptcha" class="captcha-item">
                        <el-row align="middle">
                            <el-col :span="12">
                                <!--placeholder="验证码"-->
                                <el-input v-model="form.captchaValue" class="captchaInput" maxlength="4" :placeholder="t('common.70')" clearable >
                                    <template #prefix>
                                        <Icon name="shield-check-line" size="16px"/>
                                    </template>
                                </el-input>
                            </el-col>
                            <el-col :span="7" :offset="1">
                                <el-image :src="form.imgUrl" @click="replaceCaptcha"/>
                            </el-col>
                            <el-col :span="3" :offset="1">
                                <!--换一幅-->
                                <el-link type="primary" @click="replaceCaptcha" :underline="false" class="replaceCaptchaText">{{t('common.80')}}</el-link>
                            </el-col>
                        </el-row>
                    </el-form-item>
                    <el-form-item>
                        <!--提交-->
                        <el-button type="primary" size="large" style="width: 130px;" @mousedown.native="onSubmit"  :disabled="form.allowSubmit">{{t('common.50')}}</el-button>
                    </el-form-item>
                </el-form>
                <!--title="发表话题功能已关闭"-->
                <el-result v-if="!form.allowTopic" icon="warning" :title="t('addTopic.160')"></el-result>

                <!-- 选择提及用户 -->
                <div class="selectMentionUserModule">
                    <!-- title="选择用户" -->
                    <el-dialog :title="t('addTopic.210')" :z-index="900000" v-model="form.popup_mentionUser" @close="closeMentionUser" :draggable="true" top="40vh" width="500">
                        <div class="search">
                            <el-form :inline="true" label-width="auto" @keyup.enter.native="searchMentionUser">
                                <el-form-item :error="error.keyword">
                                    <!-- placeholder="用户账号或呢称" -->
                                    <el-input v-model.trim="form.keyword" maxlength="30" :clearable="true" :placeholder="t('addTopic.220')"></el-input>
                                </el-form-item>
                                
                                <el-form-item >
                                    <!-- 搜索 -->
                                    <el-button type="primary" size="large" class="submitButton" @click="searchMentionUser" >{{t('addTopic.230')}}</el-button>
                                </el-form-item>
                                
                            </el-form>
                        </div>
                        <div class="mentionUserItem" v-for="mentionUser in form.mentionUserList" @click="selectMentionUser(mentionUser)">
                            <div class="left-layout">
                                <div class="avatarBox">
                                   
                                    <img v-if="mentionUser.avatarName != null" :src="mentionUser.avatarPath+'100x100/'+mentionUser.avatarName" class="img">
                                    <img v-if="mentionUser.avatarName == null" :src="mentionUser.avatar" width="48" height="48" class="img"/>
                                     
                                </div>
                            </div>
                            <div class="right-layout">
                                <span class="userInfo">{{mentionUser.nickname != null && mentionUser.nickname != '' ?mentionUser.nickname : mentionUser.account}}</span>
                            </div>
                        </div>
                    </el-dialog>
                </div>
            </div>
        </div>
    </div>


    <!-- 页脚 -->
    <Footer/>
</template>

<script setup lang="ts">
    import { onMounted, ref ,nextTick, getCurrentInstance, ComponentInternalInstance, reactive, onUnmounted, computed, watch,} from 'vue'
    import { dayjs, ElMessage, ElNotification, FormInstance} from 'element-plus'
    import { useRouter } from 'vue-router'
    import { useMeta} from 'vue-meta';
    import { appStore } from "@/store";
    import { AxiosResponse } from 'axios';
    import { Tag, User } from '@/types';
    import { onBeforeRouteUpdate } from 'vue-router';
    import { calc_add, calc_multiply, processErrorInfo } from '@/utils/tool';
    import { createEditor } from '@/utils/editor';
    import { markdownPlugins,markdownEditorConfig,sanitize, markdownToHtml, setMarkdownLanguage } from '@/utils/markdownEditor';
    import { toggleEditor } from '@/utils/markdownPlugin/plugin-toggle-editor';
    import { help } from '@/utils/markdownPlugin/plugin-help';
    import { emoji } from '@/utils/markdownPlugin/plugin-emoji';
    import { imageUpload } from '@/utils/markdownPlugin/plugin-image-upload';
    import { pasteImageUpload } from '@/utils/markdownPlugin/plugin-paste-image';
    import { fileUpload } from '@/utils/markdownPlugin/plugin-file-upload';
    import { videoUpload } from '@/utils/markdownPlugin/plugin-video-upload';
    import { hideContent } from '@/utils/markdownPlugin/plugin-hide-content';
    import type { BytemdPlugin,BytemdEditorContext } from 'bytemd'
    import { Editor } from '@bytemd/vue-next'
    import { mention } from '@/utils/markdownPlugin/plugin-mention';
    import { letterAvatar } from '@/utils/letterAvatar';
    import { ai } from '@/utils/markdownPlugin/plugin-ai';
    import { aiPopUp } from '@/components/aiAssistant/aiAssistantTool';
    import { Top, Bottom,Delete,Plus} from '@element-plus/icons-vue'
    import { useI18n } from 'vue-i18n';
    let { t } = useI18n();

    const store = appStore();
    const router = useRouter();
    const { proxy,appContext } = getCurrentInstance() as ComponentInternalInstance;

    const formMobileRef = ref<FormInstance>();
    const contentRef = ref()

    //html页元信息
    const { meta } = useMeta(
        computed(() => ({ 
            title:  t('addTopic.240')+' - ' + store.state.title,//发表话题
            meta: [
                {
                    name: 'keywords',
                    content: t('addTopic.240')+' - ' + store.state.title//发表话题
                },{
                    name: "description",
                    content: t('addTopic.240')+' - ' + store.state.title//发表话题
                }
            ]
        }))
    )

    interface VoteOptionItem {
        id: string;
        text: string;
    }

    const form = reactive({
        emojiIndex:"",

        tagList:[] as Array<Tag>,//标签
        deposit:'',//用户共有预存款
        allowTopic:true,//是否允许提交话题
        giveRedEnvelopeAmountMin:'',//发红包金额下限
        giveRedEnvelopeAmountMax:'',//发红包金额上限  空为无限制 0则不允许发红包 
        userGradeList:[],//用户等级
        availableTag:[] as Array<string>,//话题编辑器允许使用标签
        fileSystem:0,//文件存储系统
        supportEditor:10,//支持编辑器
        allowTagIdList:[] as Array<string>,//有提交权限的标签Id

        popup_mentionUser :false,//是否弹出选择提及用户表单
        keyword :'',//关键词
        mentionUserList:[] as Array<User>,//提及用户集合
        mentionUserEditorId:'',//提及用户编辑器Id
        currentMarkdownEditor:{} as BytemdEditorContext | undefined,//Markdown编辑器打开‘@提及’弹窗的编辑器对象

        showRedEnvelopeText:false,//显示发红包按钮
        showRedEnvelopeForm:false,//显示发红包表单
        giveRedEnvelope_type:20, //发红包类型
		giveRedEnvelope_totalAmount:'',//红包总金额
		giveRedEnvelope_singleAmount:'',//红包单个金额
		giveRedEnvelope_giveQuantity:'',//红包数量
		giveRedEnvelope_totalAmountView:'0.00',//红包合计总金额

        maxVoteOptions :0,//发起投票选项数量
        isVoteView:false,//是否显示发起投票
        isVote:false,//是否发起投票
        voteTitle :'',
        voteMaxChoice :1,
        voteEndDate_format:'',
        voteEndDate :'',//截止时间
        voteOptions: [{
            id: '',
            text: ''
        }] as Array<VoteOptionItem>,

        isAllowLoadTagGroup:true,//是否允许加载标签组
        tagIdGroup :[],//标签Id组
        loading :false,//是否正在从远程获取数据

        tagId:'',//标签Id
        title:'',//标题
        content:'',//内容
        markdownContent:'',//markdown内容
        isMarkdown:false,//是否使用markdown编辑器

        showCaptcha:false,//是否显示验证码
        captchaKey: '',//验证码key
        captchaValue: '',//验证码值
        imgUrl: '',//验证码图片
        allowSubmit:false,//提交按钮disabled状态

        addTopicEditor :{} as any,//添加话题编辑器
		addTopicEditorCreateParameObject :{} as any,//添加话题编辑器的创建参数

        addTopicEditorPlugin:[] as BytemdPlugin[],//添加话题Markdown编辑器插件
    });

    //错误
    const error = reactive({
        tagId:'',//标签Id
        title:'',//标题
        content:'',//内容
        totalAmount:'',//红包总金额
        singleAmount:'',//单个红包金额
		giveQuantity: '',//红包数量
		redEnvelopeLimit: '',//合计总金额
        captchaValue:'',//验证码

        keyword :'',
        voteOption :'',
        voteTitle :'',
        voteMaxChoice :'',
        voteEndDate :'',
    })

    //处理Markdown
    const handleMarkdownChange = (value: string) => {
        form.markdownContent = value;
    }

    //白名单
    const addTopicSanitize = (schema: any) => {
        schema = sanitize(schema);
        
        if(form.availableTag?.indexOf('embedVideo') != -1){//嵌入视频
            schema.tagNames.push('iframe');
        }

        return schema;
    }

    //markdown生成Html
    const onHtml = () => {
        let html = markdownToHtml(addTopicSanitize,form.addTopicEditorPlugin,form.markdownContent);
        console.log("Html内容--",html);
    }
    



    //处理切换到富文本编辑器
    const handleToggleRichtextEditor = (editorId: string) => {
        form.isMarkdown = false;
        nextTick(()=>{
            if (Object.keys(form.addTopicEditorCreateParameObject).length != 0) {//不等于空
                //创建富文本编辑器
                form.addTopicEditor = createEditor(
                    form.addTopicEditorCreateParameObject.ref, 
                    form.addTopicEditorCreateParameObject.availableTag, 
                    form.addTopicEditorCreateParameObject.uploadPath, 
                    form.addTopicEditorCreateParameObject.userGradeList,
                    form.fileSystem,
                    ()=>{
                        handleToggleMarkdownEditor(editorId);
                    },
                    ()=>{
                        //提及弹窗
                        mentionPopUp(editorId,undefined)
                    },
                    ()=>{
                        //AI弹窗
                        aiPopUp(proxy,appContext,editorId,form.addTopicEditorCreateParameObject.uploadPath,'file',form.fileSystem,form.isMarkdown,form.addTopicEditor,undefined)
                    }
                );
            }
        })
        
        
    }

    //处理切换到Markdown编辑器
    const handleToggleMarkdownEditor = (editorId: string) => {
        if (Object.keys(form.addTopicEditor).length != 0) {//不等于空
			form.addTopicEditor.remove();
            form.addTopicEditor = {};
		}
        form.isMarkdown = true;
    }

    //是否有提交权限的标签
    const isAllowTag = (tagId:string) => {
        for (let i = 0; i < form.allowTagIdList.length; i++){
            if (form.allowTagIdList[i] == tagId){
                return true;
            }
        }
        return false;
    }
    
    //投票 添加项
    const addItem = () => {
        if(form.voteOptions.length >= form.maxVoteOptions){
            ElMessage({
                showClose: true,
                message: t('addTopic.290',{'p1': form.maxVoteOptions}),//投票选项不能超过 {p1} 项
                type: 'warning',
            })
            return;
        }
        

        form.voteOptions.push({
            id: '',
            text: ''
        });
    }
    //投票 删除项
    const removeItem = (voteOption:any) => {
        let index = form.voteOptions.indexOf(voteOption);
        if (index !== -1) {
            form.voteOptions.splice(index, 1);
        }
    }
    //投票 上移
    const moveUp = (voteOption:any) => {
        let index = form.voteOptions.indexOf(voteOption);
        if (index >0) {
            let upData = form.voteOptions[index - 1];
            form.voteOptions.splice(index - 1, 1);
            form.voteOptions.splice(index, 0, upData);
        }
    }
    //投票 下移
    const moveDown = (voteOption:any) => {
        let index = form.voteOptions.indexOf(voteOption);
        if ((index + 1) < form.voteOptions.length) {
            let downData = form.voteOptions[index + 1];
            form.voteOptions.splice(index + 1, 1);
            form.voteOptions.splice(index, 0, downData);
        }
    }


    //查询标签
    const queryTagList = () => {
        if(!form.isAllowLoadTagGroup){
	        return;
	    }

        proxy?.$axios({
            url: '/allTag',
            method: 'get',
            params:  {},
            showLoading: false,//是否显示加载图标
            loadingMask:false,// 是否显示遮罩层
        })
        .then((response: AxiosResponse) => {
            return response?.data
        })
        .then((data: Array<Tag>) => {
            form.isAllowLoadTagGroup = false;
            form.tagList = data;
        })
        .catch((error: any) =>{
            console.log(error);
        });

    }

    //显示、隐藏提及弹窗
    const mentionPopUp = (editorId: string,ctx:BytemdEditorContext| undefined) => {
       // console.log("显示、隐藏提及弹窗",editorId);
      
        form.popup_mentionUser = true;
        form.mentionUserEditorId = editorId;
        form.keyword = "";
        form.mentionUserList.length = 0;
        form.currentMarkdownEditor = ctx;
        error.keyword = "";
    }

    //关闭提及用户弹出框
    const closeMentionUser = () => {
        form.popup_mentionUser = false;
        form.currentMarkdownEditor = undefined;
    }

    //选择提及用户
    const selectMentionUser = (mentionUser:User) => {
        let url = "user/control/home?userName="+mentionUser.userName;
        let title = mentionUser.nickname != null && mentionUser.nickname != '' ? '@'+mentionUser.nickname : '@'+mentionUser.account;

        if(form.isMarkdown){
           form.currentMarkdownEditor?.editor.replaceSelection(`${title}`);
        }else{
            form.addTopicEditor.insertMention(url,title);
        }
        
        closeMentionUser();
    }


    //搜索提及用户
    const searchMentionUser = () => {
        form.mentionUserList.length = 0
        error.keyword = "";
        if(form.keyword == null || form.keyword.trim() == ''){
            error.keyword = t('addTopic.250');//请输入用户账号或呢称
            return;
        }
        proxy?.$axios({
            url: '/user/control/queryUser',//暂时使用查询提及用户API
            method: 'get',
            params:  {keyword:form.keyword},
            showLoading: false,//是否显示加载图标
            loadingMask:false,// 是否显示遮罩层
        })
        .then((response: AxiosResponse) => {
            if(response){
                const result: any = response.data;
                if(result != ""){
                    let mentionUser = JSON.parse(result)
                
                    if(mentionUser != null){
                        let userList = new Array();
                        if(mentionUser.nickname != null && mentionUser.nickname !=''){
                            mentionUser.avatar = letterAvatar(mentionUser.nickname, 48);
                        }else{
                            mentionUser.avatar = letterAvatar(mentionUser.account, 48);
                        }
                        userList.push(mentionUser);
                        
                        form.mentionUserList = userList;
                    }else{
                        error.keyword = t('addTopic.260');//当前用户不存在
                    }
                }
            }
        })
        .catch((error: any) =>{
            console.log(error);
        });

    }



    //查询发表话题页
    const queryAddTopic = () => {
        //清空error的属性值
        Object.keys(error).map(key => {
            Object.assign(error, {[key] : ''});
        })
        //重置表单
        formMobileRef.value?.resetFields();

        proxy?.$axios({
            url: '/user/queryAddTopic',
            method: 'get',
            params:  {},
            showLoading: false,//是否显示加载图标
            loadingMask:false,// 是否显示遮罩层
        })
        .then((response: AxiosResponse) => {
            if(response){
                let data =  response.data;
                
                form.allowTopic = data.allowTopic;//是否允许提交话题

                if(data.allowTopic){
                    form.deposit = data.deposit;//用户共有预存款
                    form.giveRedEnvelopeAmountMin = data.giveRedEnvelopeAmountMin;//发红包金额下限
                    form.giveRedEnvelopeAmountMax = data.giveRedEnvelopeAmountMax;//发红包金额上限  空为无限制 0则不允许发红包 
                    if(data.userGradeList != null && data.userGradeList != ''){
                        form.userGradeList = JSON.parse(data.userGradeList);//JSON转为对象
                    }
                    form.allowTagIdList = data.allowTagIdList;//有提交权限的标签Id

                    if(data.availableTag != null && data.availableTag != ''){
                        let availableTagObject = JSON.parse(data.availableTag);//JSON转为对象

                        let flag = false;
                        if(availableTagObject != null && availableTagObject.length >0){
                            for(let i=0; i< availableTagObject.length; i++){
                                let availableTag = availableTagObject[i];
                                if(availableTag == "hidePassword" || availableTag == "hideComment" ||
                                availableTag == "hideGrade" || availableTag == "hidePoint" || availableTag == "hideAmount"){
                                    availableTagObject.splice(i, 0, 'hide');//在指定索引处插入元素
                                    break;
                                }
                            }
                            for(var i=0; i< availableTagObject.length; i++){
                                let availableTag = availableTagObject[i];
                                if(availableTag == "image"){//增加批量插入图片按钮
                                    availableTagObject.splice(i+1, 0, 'multiimage');//在指定索引处插入元素
                                    break;
                                }
                            }
                        }

                        if(data.supportEditor == 30 || data.supportEditor == 40){
                            availableTagObject.push("toggleEditor");
                        }
                        form.availableTag = availableTagObject;//话题编辑器允许使用标签
                    }
                    
                    form.fileSystem = data.fileSystem;//文件存储系统
                    form.supportEditor = data.supportEditor;//支持编辑器 10.仅富文本编辑器 20.仅Markdown编辑器  30.富文本编辑器优先 40.Markdown编辑器优先
                

                    if(data.giveRedEnvelopeAmountMax == null || (data.giveRedEnvelopeAmountMax != null && parseInt(data.giveRedEnvelopeAmountMax) >0)){
                        //显示发红包
                        form.showRedEnvelopeText = true;
                    }

                    form.maxVoteOptions = data.maxVoteOptions;
                    if(data.maxVoteOptions != null){
                        if(data.maxVoteOptions >0){//发起投票选项数量
                            form.isVoteView = true;//是否显示发起投票
                        }
                    }else{
                        form.isVoteView = true;//是否显示发起投票
                    }
                    

                    if (data.captchaKey != undefined && data.captchaKey != '') {
                        form.showCaptcha = true;
                        form.captchaKey = data.captchaKey;
                        replaceCaptcha();//刷新验证码
                    }

                    if(form.supportEditor == 20 || form.supportEditor == 40){
                        form.isMarkdown = true;
                    }

                    let uploadPath = "user/control/topic/upload?method=upload";
                    if(form.addTopicEditorPlugin != null && form.addTopicEditorPlugin.length ==0){
                        //添加插件
                        form.addTopicEditorPlugin.push(...markdownPlugins);

                        form.addTopicEditorPlugin.push(emoji());


                        if(form.availableTag?.indexOf('mention') != -1){
                            form.addTopicEditorPlugin.push(
                                mention((editorId: string,ctx:BytemdEditorContext)=>{mentionPopUp(editorId,ctx)})
                            );
                        }

                        
                        if(form.supportEditor == 30 || form.supportEditor == 40){//10.仅富文本编辑器 20.仅Markdown编辑器  30.富文本编辑器优先 40.Markdown编辑器优先
                            form.addTopicEditorPlugin.push(
                                toggleEditor((editorId: string)=>{handleToggleRichtextEditor(editorId)})
                            );
                        }
                        form.addTopicEditorPlugin.push(
                            help(form.availableTag,form.userGradeList)
                        );

                        if(form.availableTag?.indexOf('insertfile') != -1){
                            form.addTopicEditorPlugin.push(
                                fileUpload("user/control/topic/upload?method=upload",'file',form.fileSystem)
                            );
                        }
                        if(form.availableTag?.indexOf('image') != -1){
                            form.addTopicEditorPlugin.push(
                                imageUpload("user/control/topic/upload?method=upload",'file',form.fileSystem)
                            );
                            form.addTopicEditorPlugin.push(
                                pasteImageUpload("user/control/topic/upload?method=upload",'file',form.fileSystem)
                            );
                        }  

                        if(form.availableTag?.indexOf('uploadVideo') != -1){
                            form.addTopicEditorPlugin.push(
                                videoUpload("user/control/topic/upload?method=upload","file",form.fileSystem)
                            );
                        }
                        if(form.availableTag?.indexOf('hidePassword') != -1 
                            || form.availableTag?.indexOf('hideComment') != -1
                            || form.availableTag?.indexOf('hideGrade') != -1 
                            || form.availableTag?.indexOf('hidePoint') != -1 
                            || form.availableTag?.indexOf('hideAmount') != -1
                            ){
                            form.addTopicEditorPlugin.push(
                                hideContent(form.availableTag,form.userGradeList)
                            );
                        }
                        if(form.availableTag?.indexOf('ai') != -1){
                            form.addTopicEditorPlugin.push(
                                
                                ai((editorId: string,ctx:BytemdEditorContext)=>{aiPopUp(proxy,appContext,editorId,uploadPath,'file',form.fileSystem,form.isMarkdown,undefined,ctx)})
                            );
                        }
                    }

                    
                    if (Object.keys(form.addTopicEditorCreateParameObject).length === 0) {//等于空
                        
                        if(!form.isMarkdown){
                            //创建富文本编辑器
                            form.addTopicEditor = createEditor(contentRef.value, form.availableTag, uploadPath, form.userGradeList,form.fileSystem,(editorId: string)=>{
                                handleToggleMarkdownEditor(editorId);
                            },
                            (editorId: string)=>{
                                //提及弹窗
                                mentionPopUp(editorId,undefined)
                            },
                            (editorId: string)=>{
                                //AI弹窗
                                aiPopUp(proxy,appContext,editorId,uploadPath,'file',form.fileSystem,form.isMarkdown,form.addTopicEditor,undefined)
                            });
                        }
                        form.addTopicEditorCreateParameObject = {
                            ref:contentRef.value,
                            availableTag:form.availableTag,
                            uploadPath:uploadPath,
                            userGradeList:form.userGradeList
                        }
                    }
                   
                    
                }
                
            }
        })
        .catch((error: any) =>{
            console.log(error);
        });

    }

    //选中标签
    const selectedTag = (val:string) => {
        form.tagId = val;
    }

     
    //刷新验证码
    const replaceCaptcha = () => {
        form.imgUrl = store.state.apiUrl+"captcha/" + form.captchaKey + ".jpg?" + Math.random();

    }
    //校验验证码
    const checkCaptchaValue = (rule: any, value: any, callback: any) => {
        if(form.captchaKey != null && form.captchaKey != ''){
            if (value === '') {
                return callback(new Error(t('common.10')));//验证码不能为空
            }else{
                if (value.trim().length < 4) {
                    callback(new Error(t('common.20')))//验证码长度为4个字符
                } else {   
                    if(form.allowSubmit){//按下提交按钮则不再请求校验验证码
                        callback();
                        return;
                    }
                    proxy?.$axios({
                        url: '/userVerification',
                        method: 'get',
                        params:  {
                            captchaKey:form.captchaKey,
                            captchaValue:form.captchaValue
                        }
                    })
                    .then((response: AxiosResponse) => {
                        if(form.allowSubmit){//按下提交按钮则不再处理校验验证码
                            callback();
                            return;
                        }
                        if(response){
                            const result: any = response.data;
                            if(!JSON.parse(result)){
                                callback(new Error(t('common.30')))//验证码错误
                            }else{
                                callback();
                            }
                        }
                    }).catch((error: any) =>{
                        console.log(error);
                    });
                }

            }
        }
    }


    //控制只能输入小数点后2位
    const clearNoNum = (val:string) => {
        val = val.replace(/[^\d.]/g, "");  //清除“数字”和“.”以外的字符   
        val = val.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的   
        val = val.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
        val = val.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');//只能输入两个小数   
        if (val.indexOf(".") < 0 && val != "") {//以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额  
            val = parseFloat(val).toString();
        }
        return val;
    }


    //选择红包类型
    const selectRedEnvelopeType = () => {
        if(form.giveRedEnvelope_type == 20){//随机
            totalAmountCalculate();
            
        }else if(form.giveRedEnvelope_type == 30){//固定
            singleAmountCalculate();
        }
       
        
    }
    //总金额计算
    const totalAmountCalculate = () => {
        //红包总金额输入限制
        form.giveRedEnvelope_totalAmount = clearNoNum(form.giveRedEnvelope_totalAmount);

        
        if(form.giveRedEnvelope_type == 20){//随机
            let exp = /(^[1-9]([0-9]+)?(\.[0-9]{1,10})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
            if(exp.test(form.giveRedEnvelope_totalAmount.trim())) {
                let amount = calc_add(form.giveRedEnvelope_totalAmount.trim(), '0', 2);
                form.giveRedEnvelope_totalAmountView = String(amount);
            }else{
                form.giveRedEnvelope_totalAmountView = '0.00';
            }
            
        }
    }
		
    //单个红包金额计算
    const singleAmountCalculate = () => {
        //单个红包金额输入限制
        form.giveRedEnvelope_singleAmount = clearNoNum(form.giveRedEnvelope_singleAmount);

       
        if(form.giveRedEnvelope_type == 30){//固定
            //金额 只允许正数  正则判断最多10位小数
            var exp_singleAmount = /(^[1-9]([0-9]+)?(\.[0-9]{1,10})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
            //数量 正整数
            var exp_giveQuantity = /^\+?[1-9][0-9]*$/;
            if(exp_singleAmount.test(form.giveRedEnvelope_singleAmount.trim()) && exp_giveQuantity.test(form.giveRedEnvelope_giveQuantity.trim())) {
                var amount = calc_multiply(form.giveRedEnvelope_singleAmount.trim(), form.giveRedEnvelope_giveQuantity.trim(), 2);
                form.giveRedEnvelope_totalAmountView = String(amount);
            }else{
                form.giveRedEnvelope_totalAmountView = '0.00';
            }
        }
        
    }

    //校验规则
    const rules = reactive({
       captchaValue: [{ validator: checkCaptchaValue, trigger: 'blur' }],
    })

    //提交数据
    const onSubmit = () => {
        form.allowSubmit = true;//提交按钮disabled状态

        const p1 = new Promise<void>((resolve, reject) => {
            formMobileRef.value?.validate((valid: boolean) => {
                if (valid) {
                    resolve();
                }else{
                    form.allowSubmit = false;//提交按钮disabled状态
                }
            })
            
        });

        Promise.all([p1])
            .then(() => {
                //清空error的属性值
                Object.keys(error).map(key => {
                    Object.assign(error, {[key] : ''});
                })
            

                let formData = new FormData();
                formData.append('tagId', form.tagId);

                if(form.title != null && form.title != ''){
                    formData.append('title', form.title);
                }

                if(form.isMarkdown){
                    formData.append('isMarkdown', form.isMarkdown.toString());
                    formData.append('markdownContent', form.markdownContent);
                }else{
                    if(contentRef.value.value != null && contentRef.value.value !=''){
                        formData.append('content', contentRef.value.value);
                    }
                }

                

                //如果显示红包表单
                if(form.showRedEnvelopeForm){
                    formData.append('type', String(form.giveRedEnvelope_type));//发红包类型
                    formData.append('totalAmount', form.giveRedEnvelope_totalAmount);//红包总金额
                    formData.append('singleAmount', form.giveRedEnvelope_singleAmount);//单个红包金额
                    formData.append('giveQuantity', form.giveRedEnvelope_giveQuantity);//红包数量
                }

                formData.append('isVote', form.isVote.toString());
                if(form.voteTitle != null && form.voteTitle != ''){
                    formData.append('voteTitle', form.voteTitle);
                }
                formData.append('voteMaxChoice', String(form.voteMaxChoice));
                if(form.voteEndDate_format != null && form.voteEndDate_format != ''){
                    form.voteEndDate = dayjs(form.voteEndDate_format).format('YYYY-MM-DD HH:mm:ss');
                }else{
                    form.voteEndDate = '';
                }
                formData.append('voteEndDate', form.voteEndDate);

                if(form.voteOptions != null && form.voteOptions.length >0){
                    for(let i=0; i<form.voteOptions.length; i++){
                        let voteOption = form.voteOptions[i];
                        formData.append('voteOptionTextList', voteOption.text);
                        
                    }
                }

                
                //验证码Key
                formData.append('captchaKey', form.captchaKey);
                //验证码值
                if(form.captchaValue != ''){
                    formData.append('captchaValue', form.captchaValue.trim());
                }

                proxy?.$axios({
                    url: '/user/control/topic/add',
                    method: 'post',
                    data: formData
                })
                .then((response: AxiosResponse) => {
                    if(response){

                        const result: any = response.data;
                        
                        if(JSON.parse(result.success)){
                            ElMessage({
                                showClose: true,
                                message: t('addTopic.270'),//提交成功，3秒后自动跳转到首页
                                type: 'success',
                                onClose: ()=>{
                                        router.push({
                                        path : '/'
                                    });
                                }
                            })


                        }else{
                            //处理错误信息
                            processErrorInfo(result.error as Map<string,string> , error,()=>{});
                            

                            

                            if(result.captchaKey != null){
                                form.showCaptcha = true;
                                form.captchaKey = result.captchaKey;
                                replaceCaptcha();
                            }else{
                                form.showCaptcha = false;
                            }

                            form.allowSubmit = false;//提交按钮disabled状态
                        }
                    }
                })
                .catch((error: any) =>{
                    console.log(error);
                    form.allowSubmit = false;//提交按钮disabled状态
                });
            }).catch(() => {
                console.log("提交数据错误");
            });
        

    }



    //导航守卫
    onBeforeRouteUpdate((to, from, next) => {
        if(to.name == 'addTopic'){
            queryAddTopic();
            queryTagList();
        }
        
        next();
    });

    onMounted(() => {
        queryAddTopic();
        queryTagList();

    }) 

    //卸载组件实例后调用
    onUnmounted (()=>{
        if (Object.keys(form.addTopicEditor).length != 0) {//不等于空
            form.addTopicEditor.remove();
            form.addTopicEditor = {};
        }
    })
</script>



<style scoped lang="scss">
.option-group{
    margin-left: 24px;
}
//隐藏选择器分组分割线
.el-select-group__wrap:not(:last-of-type) {
     padding-bottom: 0px;
}
.el-select-group__wrap:not(:last-of-type)::after {
    height: 0px;
}
.addTopicModule{
    background: #fff;
    padding:25px 40px 40px 40px;
    margin:0px auto;

    :deep(.bytemd){
        height: calc(100vh - 100px);
        
    }
    :deep(.CodeMirror-scroll){//让外层滚动条不滚动
        overscroll-behavior:  contain;
    }
    :deep(.bytemd-preview){//让外层滚动条不滚动
        overscroll-behavior:  contain;
    }
    
    .form-text{
        margin-right: 15px;
    }
    .help-text{
        font-size: 13px;
        color: $color-black-50;
        line-height: 38px;
    }
    .totalAmountView{
        margin-left: 10px;
        font-size: 18px;
    }

    //图标表单
    .iconForm-container{
        margin-top: 15px;
        :deep(.el-form-item__content) {
            line-height: normal;
        }
        :deep(.el-form-item__error) {
            width: 100%;
        }
        :deep(.el-select__wrapper){
            background-color: #f7f8fa;
            box-shadow: 0 0 0 1px #f7f8fa inset;
        }
        .captcha-item{
            .captchaInput{
                width: 160px;
            }
            :deep(.el-form-item__error){
                width: 100%;
            }
            .replaceCaptchaText{
                position: relative;
                top: -1px;
                user-select:none;
                :deep(.el-link__inner){
                    white-space:nowrap;
                }
            }
        }
        


    }

    /** 选择提及用户 **/
    .selectMentionUserModule {
        background: #fff;
        :deep(.search){
            
            .el-form--inline .el-form-item{
                margin-right: 10px;
            }

            .el-form-item__content {
                line-height: 40px;
            }
            .el-radio-button__inner{
                padding: 12px 20px 12px 20px;
            }
            .el-input {
                --el-input-height: 40px;
                width: 178px;
            }
            .el-form-item__error{
                font-size: 13px; padding-top: 8px;
            }
            .form-help{
                color: #909399; 
                line-height: 20px;
                margin-top: 8px;
            }
        }
        .mentionUserItem{
            margin-top: 15px;
            padding: 8px;
            margin-left: -8px;
            margin-right: -8px;
            cursor: pointer;
            display: flex;
            &:hover{
                background: $color-black-10;
                border-radius:3px;
            }
            .left-layout{
                margin-right: 10px;
                width: 48px;
                .avatarBox {
                  
                    img {
                        float: none;
                        display: block;
                        width: 48px;
                        height: 48px;
                        float: left;
                        margin-right: 10px;
                        border-radius:48px;
                        position:relative;
                    }
                    
                }
            }
            .right-layout{
                flex: 1;
                
                .userInfo{
                    line-height: 48px;
                }
            }
        }
    }

}

</style>